package com.cskaoyan.service.impl;

import com.cskaoyan.bean.MarketPermission;
import com.cskaoyan.bean.MarketRole;
import com.cskaoyan.bean.MarketRoleExample;
import com.cskaoyan.bean.zhangshizhi.web.role.*;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * @author little ants（张时智）
 * @since 2022/06/25 17:20
 */

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    MarketRoleMapper mapper;
    @Autowired
    MarketPermissionMapper permissionMapper;
    @Autowired
    MarketAdminMapper adminMapper;


    /**
     * 获取角色信息
     *
     * @param roleBO
     * @return com.cskaoyan.bean.zhangshizhi.web.role.RoleListVO
     * @author little ants
     * @since 2022/06/28 19:56
     */

    @Override
    public RoleListVO getRoleList(RoleListBO roleBO) {


        MarketRoleExample marketRoleExample = new MarketRoleExample();
        marketRoleExample.setOrderByClause(roleBO.getSort() + " " + roleBO.getOrder());
        MarketRoleExample.Criteria criteria = marketRoleExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (roleBO.getName() != null && !Objects.equals(roleBO.getName(), "")) {
            criteria.andNameLike("%" + roleBO.getName() + "%");
        }


        PageHelper.startPage(roleBO.getPage(), roleBO.getLimit());
        List<MarketRole> list = mapper.selectByExample(marketRoleExample);

        PageInfo<MarketRole> pageInfo = new PageInfo<>(list);

        RoleListVO roleListVO = new RoleListVO();

        roleListVO.setList(list);
        roleListVO.setLimit(roleBO.getLimit());
        roleListVO.setPage(roleBO.getPage());
        roleListVO.setTotal((int) pageInfo.getTotal());
        roleListVO.setPages(pageInfo.getPages());

        return roleListVO;
    }

    /**
     * 添加角色
     *
     * @param role
     * @return com.cskaoyan.bean.MarketRole
     * @author little ants
     * @since 2022/06/28 15:41
     */
    @Override
    public MarketRole addRole(MarketRole role) {

        Date date = new Date();

        role.setAddTime(date);
        role.setUpdateTime(date);

        mapper.insertSelective(role);

        MarketRole newRole = mapper.selectByRole(role);
        return newRole;
    }

    /**
     * 删除角色信息
     *
     * @param role
     * @return void
     * @author little ants
     * @since 2022/06/28 15:40
     */
    @Override
    public void deleteRole(MarketRole role) {

        MarketRole marketRole = new MarketRole();
        marketRole.setId(role.getId());
        marketRole.setDeleted(true);
        mapper.updateByPrimaryKeySelective(marketRole);

    }

    /**
     * 更新角色信息
     *
     * @param role
     * @return void
     * @author little ants
     * @since 2022/06/28 15:40
     */
    @Override
    public void updateRole(MarketRole role) {
        mapper.updateByPrimaryKeySelective(role);
    }

    /**
     * 获取当前角色的权限
     *
     * @param roleId
     * @return com.cskaoyan.bean.zhangshizhi.web.role.PermissionsVO
     * @author little ants
     * @since 2022/06/28 15:39
     */
    @Override
    public PermissionsVO selectRolePermissions(Integer roleId) {

        List<SystemPermissions> permissions = mapper.selectAllSystemPermissions();

        for (SystemPermissions permission : permissions) {
            addChildren(permission, permissions);
        }

        Iterator<SystemPermissions> iterator = permissions.iterator();
        while (iterator.hasNext()) {
            SystemPermissions next = iterator.next();
            if (next.getParent() != null) {
                iterator.remove();
            }
        }


        List<String> assignedPermissions = mapper.selectAllAssignedPermissions(roleId);

        PermissionsVO permissionsVO = new PermissionsVO();
        permissionsVO.setSystemPermissions(permissions);
        permissionsVO.setAssignedPermissions(assignedPermissions);

        return permissionsVO;
    }

    /**
     * 授权
     *
     * @param permissionsBO
     * @return void
     * @author little ants
     * @since 2022/06/28 19:10
     */
    @Override
    public void updateRolePermissions(RolePermissionsBO permissionsBO) {
        // 先删除旧权限
        permissionMapper.deleteByPrimaryKey(permissionsBO.getRoleId());

        // 获取系统权限总数
        Integer countOfPermissionApi =mapper.countOfPermissionApi();

        if (permissionsBO.getPermissions().size() != countOfPermissionApi) {
            // 普通管理员
            permissionMapper.insertPermissions(permissionsBO.getPermissions(), permissionsBO.getRoleId());
            return;
        }
        if (permissionsBO.getPermissions().size() == countOfPermissionApi) {
            // 超级管理员
            MarketPermission permission = new MarketPermission();
            permission.setRoleId(permissionsBO.getRoleId());
            permission.setPermission("*");
            Date date = new Date();
            permission.setAddTime(date);
            permission.setUpdateTime(date);
            permission.setDeleted(false);

            permissionMapper.insert(permission);
        }

    }

    /**
     * 获取角色的信息
     *
     * @return com.cskaoyan.bean.zhangshizhi.web.role.RoleSimpleListVO
     * @author little ants
     * @since 2022/06/30 1:27
     */
    @Override
    public RoleSimpleListVO getAllRoleSimpleInfo() {

        PageHelper.startPage(1, 20);
        List<RoleSimpleInfo> roleSimpleInfoList = mapper.selectSimpleRole();

        PageInfo<RoleSimpleInfo> pageInfo = new PageInfo<>(roleSimpleInfoList);

        RoleSimpleListVO roleSimpleListVO = new RoleSimpleListVO();
        roleSimpleListVO.setPage(1);
        roleSimpleListVO.setLimit(20);
        roleSimpleListVO.setList(roleSimpleInfoList);
        roleSimpleListVO.setPages(pageInfo.getPages());
        roleSimpleListVO.setTotal((int) pageInfo.getTotal());

        return roleSimpleListVO;
    }


    private void addChildren(SystemPermissions permission, List<SystemPermissions> permissions) {
        for (SystemPermissions systemPermissions : permissions) {

            if (permission.getParent() != null &&
                    permission.getSuperParent() == null &&
                    systemPermissions.getSuperParent() != null &&
                    Objects.equals((systemPermissions.getParent()), permission.getLabel()) &&
                    Objects.equals(systemPermissions.getSuperParent(), permission.getParent())

            ) {
                permission.getChildren().add(systemPermissions);
                continue;
            }

            if (permission.getParent() == null &&
                    systemPermissions.getSuperParent() == null &&
                    Objects.equals((systemPermissions.getParent()), permission.getLabel())) {
                permission.getChildren().add(systemPermissions);
            }

        }
    }
}
